package xmu.crms.controller;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import xmu.crms.mapper.UserMapper;
import xmu.crms.util.JwtUtil;
import xmu.crms.vo.UrlVO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Paths;
import java.util.UUID;

/**
 *
 * @author status200
 * @date 2017/11/30
 */
@RestController
public class UploadController {

    private final Log log = LogFactory.getLog(UploadController.class);

    private final String ROOT = "/var/www/deploy/jee/xmu8102/data/avatar/";

    private ResourceLoader resourceLoader;

    private final UserMapper userMapper;
    @Autowired
    public UploadController(ResourceLoader resourceLoader, UserMapper userMapper) {
        this.resourceLoader = resourceLoader;
        this.userMapper = userMapper;
    }

    @PostMapping("/upload/avatar")
    public ResponseEntity<UrlVO> updateAvatar(@RequestParam("file") MultipartFile file,
                                              @RequestHeader("Authorization") String authString) throws IOException {

        if(!file.isEmpty()) {
            BigInteger userId = JwtUtil.getIdFromAuthString(authString);

            // 截取文件类型
            String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // uuid生成用户头像名
            String fileName = UUID.randomUUID().toString() + fileType;
            log.info(fileName);

            File dir = new File(ROOT);

            // 如果文件夹不存在，级联创建
            if(!dir.exists()) {
                dir.mkdirs();
            }
            File img = new File(Paths.get(ROOT ,fileName).toString());

            // 文件不存在，则创建
            if(!img.exists()) {
                img.createNewFile();
            }

            // 数据写入文件
            FileUtils.copyToFile(file.getInputStream(),img);

            // 更新用户的头像文件名
            userMapper.updateUserAvatarByUserId(userId,fileName);

            return new ResponseEntity<>(new UrlVO(fileName), HttpStatus.CREATED);
        }

        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    @GetMapping("/avatar/{filename:.+}")
    public ResponseEntity<?> getAvatar(@PathVariable("filename") String filename) {

        try {
            return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }


}
